<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">用户名:</span>
                        <el-input v-model="searchForm.search" placeholder="用户名" size="small"
                                  style="width: 160px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            v-model="searchForm.date"
                            type="month"
                            size="small"
                            style="width: 130px;"
                            placeholder="选择日期"
                            value-format="yyyy-M"
                        />
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">状态:</span>
                        <el-select v-model="searchForm.state" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">等级:</span>
                        <el-select v-model="searchForm.is_up" size="small" style="width: 130px;" placeholder="全部" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="萌新" value="0"></el-option>
                            <el-option label="初级服务商" value="1"></el-option>
                            <el-option label="中级服务商" value="2"></el-option>
                            <el-option label="高级服务商" value="3"></el-option>
                            <el-option label="区域服务商" value="4"></el-option>
                            <el-option label="城市服务商" value="5"></el-option>
                            <el-option label="大区服务商" value="6"></el-option>
                            <el-option label="全球服务商" value="7"></el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">渠道用户:</span>
                        <el-select v-model="searchForm.channel_id" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option v-for="(item, index) in qudaoList" :key="index" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                    <el-button type="success" size="small" style="margin-left: 10px;" @click="handleReset">重置</el-button>
                    <el-button type="success" size="small" style="margin-left: 10px;" @click="showConfirmDialog">发放</el-button>
                    <el-button size="small" @click="exportToExcel">导出</el-button>
                </div>
            </div>

            <el-table :data="tableData" height="560" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" label="ID" width="100" align="center" />
                <el-table-column prop="uid" label="用户ID" width="100" align="center" />
                <el-table-column prop="username" label="账号" width="100" align="center" />
                <el-table-column prop="name" label="渠道名称" width="100" align="center" />
                <el-table-column prop="year" label="年" width="100" align="center" />
                <el-table-column prop="month" label="月" width="100" align="center" />
                <el-table-column prop="total_price" label="渠道月份总业绩" width="150" align="center" />
                <el-table-column prop="is_up_name" label="分红时等级" width="100" align="center" />
                <el-table-column prop="ave_dis" label="平均分红" width="100" align="center" />
                <el-table-column prop="other_dis" label="加权分红" width="100" align="center" />
                <el-table-column prop="level_one_id" label="第一个业绩最小部门id" width="200" align="center" />
                <el-table-column prop="level_two_id" label="第二个最小部门id" width="200" align="center" />
                <el-table-column prop="level_one_money" label="第一个业绩最小部门业绩" width="200" align="center" />
                <el-table-column prop="level_two_money" label="第二个业绩最小部门业绩" width="200" align="center" />
                <el-table-column prop="state" label="发放状态" align="center" width="140">
                    <template slot-scope="scope">
                        <div class="status-selector">
                            <el-select
                                v-model="scope.row.state.toString()"
                                size="small"
                                @change="(val) => changeLevel(scope.row.id, val)"
                                placeholder="选择状态"
                                class="status-dropdown"
                            >
                                <el-option label="待发放" value="0"></el-option>
                                <el-option label="已发放" value="1" disabled></el-option>
                                <el-option label="不发放" value="2"></el-option>
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="申请凭证" align="center"  style="width: 8%;">
                    <template slot-scope="scope">
                        <div v-if="!scope.row.div_cert">-</div>
                        <img
                            v-if="scope.row.div_cert"
                            style="width: 50px;height: 50px"
                            :src="$appConfig.imgPath + scope.row.div_cert"
                            @click="openCertificateDialog(scope.row.div_cert)"
                        />
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total"
            />
        </div>

        <!-- 金额修改弹窗 -->
        <el-dialog
            title="修改分成金额"
            :visible.sync="amountDialogVisible"
            width="450px"
            :close-on-click-modal="false"
            center
            :before-close="handleDialogClose"
            custom-class="amount-edit-dialog"
        >
            <el-form :model="editForm" label-width="70px" class="edit-form">
                <el-form-item label="用户ID:">
                    <el-input v-model="editForm.userId" disabled class="info-item" size="small"></el-input>
                </el-form-item>
                <el-form-item label="用户名:">
                    <el-input v-model="editForm.username" disabled class="info-item" size="small"></el-input>
                </el-form-item>
                <el-form-item label="原金额:">
                    <el-input v-model="editForm.originalAmount" disabled class="info-item" size="small">
                    </el-input>
                </el-form-item>
                <el-form-item label="新金额:">
                    <el-input
                        v-model="editForm.newAmount"
                        type="number"
                        size="small"
                        placeholder="请输入新金额">
                    </el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="amountDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="handleConfirmEdit" size="small">确认</el-button>
            </div>
        </el-dialog>

        <!-- 确认修改弹窗 -->
        <el-dialog
            title="确认修改"
            :visible.sync="confirmDialogVisible"
            width="400px"
            append-to-body
            center
            custom-class="confirm-dialog"
        >
            <div class="confirm-content">
                <i class="el-icon-warning-outline warning-icon"></i>
                <div class="confirm-text">
                    <div class="confirm-title">确认修改</div>
                    <div class="confirm-desc">您确定要将金额修改吗？此操作不可撤销！</div>
                </div>
            </div>
            <div class="confirm-details">
                <div class="detail-item">
                    <span class="detail-label">用户ID:</span>
                    <span class="detail-value">{{ editForm.userId }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">用户名:</span>
                    <span class="detail-value">{{ editForm.username }}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">原金额:</span>
                    <span class="detail-value">{{ editForm.originalAmount }} </span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">新金额:</span>
                    <span class="detail-value">{{ editForm.newAmount }} </span>
                </div>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="confirmDialogVisible = false" size="small">取消</el-button>
                <el-button type="success" @click="submitAmountChange" size="small">确认修改</el-button>
            </div>
        </el-dialog>

        <el-dialog
            width="30%"
            :visible.sync="firstConfirmVisible"
            title="确认发放"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            custom-class="confirm-dialog"
        >
                <div class="confirm-content">
                    <p class="confirm-item">发放人数: <span class="value">{{ totalPeople }} 人</span></p>
                    <p class="confirm-item">发放金额: <span class="value">{{ totalAmount }} 元</span></p>
                </div>
                <!-- 分红凭证上传 -->
            <el-form>
                <el-form-item label="分红凭证：" style="margin-bottom: 10px;">
                    <el-upload
                        class="div-cert-uploader"
                        action="/admin/shop/imgUpload"
                        :headers="{ token: userInfo.token }"
                        :data="{ type: 2 }"
                        :show-file-list="false"
                        :on-success="handleDivCertSuccess"
                        :before-upload="beforeDivCertUpload"
                    >
                        <el-button v-if="!div_cert" size="small" type="primary">上传分红凭证</el-button>
                        <img v-if="div_cert" :src="$appConfig.imgPath + div_cert" alt="分红凭证" style="max-width: 100%; max-height: 120px; border: 1px solid #eee; margin-top: 5px;" />
                    </el-upload>
                </el-form-item>
            </el-form>

            <template>
                <el-button @click="firstConfirmVisible = false" size="small" style="margin-left: 32%;">取消</el-button>
                <el-button type="primary" @click="showSecondConfirm" size="small" >确认</el-button>
            </template>
        </el-dialog>

        <!-- 二级确认弹窗 -->
        <el-dialog
            width="30%"
            :visible.sync="secondConfirmVisible"
            title="再次确认"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            custom-class="confirm-dialog danger"
        >
                <div class="confirm-content danger">
                    <p class="warning-text">您是否确认发放以下内容？</p>
                    <p class="confirm-item">发放人数: <span class="value">{{ totalPeople }} 人</span></p>
                    <p class="confirm-item">发放金额: <span class="value">{{ totalAmount }} 元</span></p>
                    <div style="margin-top: 10px;">
                      <span style="font-weight: bold;">分红凭证：</span>
                      <img v-if="div_cert" :src="$appConfig.imgPath + div_cert" alt="分红凭证" style="max-width: 100%; max-height: 120px; border: 1px solid #eee; margin-top: 5px;" />
                      <span v-else style="color: #f56c6c;">未上传</span>
                    </div>
                </div>
            <template>
                <el-button @click="secondConfirmVisible = false" size="small" style="margin-left: 32%;">取消</el-button>
                <el-button type="danger" @click="confirmDistribution" size="small" :disabled="!div_cert">确认发放</el-button>
            </template>
        </el-dialog>

        <el-dialog title="申请凭证" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="true">
            <div style="text-align: center;">
                <img :src="currentQRCode" style="max-width: 100%; max-height: 800px;">
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {mapState} from "vuex";

export default {
    data() {
        return {
            qrCodeDialogVisible: false,
            firstConfirmVisible: false,
            secondConfirmVisible: false,
            totalPeople: 0, // 实际项目中从数据中获取
            totalAmount: 0 , // 实际项目中从数据中获取
            searchForm: {
                date: '',
                search: '',
                is_up: '',
                state: '',
                channel_id:""
            },
            tableData: [],
            statusOptions: [
                { label: '全部', value: '' },
                { label: '已发放', value: 1 },
                { label: '待发放', value: 0 },
                { label: '不发放', value: 2 }
            ],
            currentPage: 1,
            pageSize: 15,
            total: 0,
            // 新增的数据
            amountDialogVisible: false,
            confirmDialogVisible: false,
            editForm: {
                userId: '',
                username: '',
                originalAmount: 0,
                newAmount: 0,
                rowIndex: -1
            },
            qudaoList:[],
            isEditing: {},
            div_cert: '', // 分红凭证图片url
        }
    },
    computed:{
        ...mapState(["userInfo"])
    },
    created() {
        this.getTableData()
        this.fetchAdminList1()
        // 初始化上传headers
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        this.uploadHeaders = userInfo && userInfo.token ? { token: userInfo.token } : {};
    },
    methods: {
        openCertificateDialog(thumb) {
            this.currentQRCode = this.$appConfig.imgPath + thumb;
            this.qrCodeDialogVisible = true;
        },
        filterEmptyParams(params) {
            return Object.fromEntries(
                Object.entries(params).filter(([_, value]) => value !== '')
            );
        },
        // 显示一级确认弹窗
        showConfirmDialog() {
            // 使用辅助函数过滤空字符串参数
            this.requestParams = this.filterEmptyParams(this.searchForm);
            // 先获取发放人数和金额数据
            this.$http.get('/admin/UserWeightDiv/setUserDivMoney', {
                params: this.requestParams
            })
                .then(result => {
                    if (result.code === 200) {
                        this.totalPeople = result.data.total_num || 0;
                        this.totalAmount = result.data.total_price.toFixed(2) || 0;
                        console.log(this.totalPeople,this.totalAmount)
                        console.log(result.data)
                        this.firstConfirmVisible = true;
                        this.div_cert = '' // 打开弹窗时清空分红凭证
                    } else {
                        this.$message.error(result.msg || '获取发放信息失败');
                    }
                })
                .catch(error => {
                    console.error('请求错误:', error);
                    this.$message.error('网络错误，请重试');
                });
        },

        // 显示二级确认弹窗
        showSecondConfirm() {
            this.firstConfirmVisible = false;
            this.secondConfirmVisible = true;
        },

        // 确认发放操作
        confirmDistribution() {
            this.secondConfirmVisible = false;
            const params = {
                limit: this.pageSize,
                div_cert: this.div_cert // 分红凭证
            };
            this.requestParams = this.filterEmptyParams(this.searchForm);
            // 先获取发放人数和金额数据
            this.$http.get('/admin/UserWeightDiv/setUserDivMoneyTo', {
                params: { ...this.requestParams, ...params }
            })
                .then(result => {
                    if (result.code === 200) {
                        this.getTableData()
                    }
                })

        },

        exportToExcel() {
            // 从本地存储中获取 userInfo
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.token) {
                // 如果 token 不存在，给出提示
                this.$message.error('token 不存在，请重新登录');
                return;
            }
            const token = userInfo.token;
            // 拼接搜索条件参数
            let queryParams = `token=${token}`;
            const {state , search , date ,channel_id ,is_up} = this.searchForm;
            if (state !== undefined && state !== null && state !== '') {
                queryParams += `&state=${state}`;
            }

            if (search !== undefined && search !== null && search !== '') {
                queryParams += `&search=${search}`;
            }

            if (channel_id !== undefined && channel_id !== null && channel_id !== '') {
                queryParams += `&channel_id=${channel_id}`;
            }

            if (is_up !== undefined && is_up !== null && is_up !== '') {
                queryParams += `&is_up=${is_up}`;
            }

            if (date !== undefined && date !== null && date !== '') {
                queryParams += `&date=${date}`;
            }
            // 构造完整的 URL
            const url =this.$appConfig.baseUrl +  `admin/UserWeightDiv/userWeightDivExport?${queryParams}`;
            // 在新窗口中打开页面
            window.open(url, '_blank');
        },
        getStatusType(status) {
            switch (status) {
                case '0': return 'info';
                case '1': return 'success';
                case '2': return 'warning';
                default: return 'info';
            }
        },

        // 根据状态值获取标签效果
        getStatusEffect(status) {
            return status === '2' ? 'dark' : 'light';
        },

        // 根据状态值获取显示文本
        getStatusText(status) {
            const statusMap = {
                '0': '待发放',
                '1': '已发放',
                '2': '不发放'
            };
            return statusMap[status] || '未知';
        },

        // 调用后端接口更新状态
        changeLevel(id, status) {
            this.$http.post('/admin/UserWeightDiv/setUserWeightDivState', {id:id,state:status}).then(result => {
                if(result.code === 200){

                    this.getTableData()
                }
            });
            // 这里调用你的 changeLevel 方法
        },
        fetchAdminList1() {
            const params = {
                type: 3,
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                console.log(result)
                const newArr = []
                if(result.code === 200){
                    result.data.data.forEach(item=>{
                        newArr.push({name:item.name,id:item.id})
                    })
                    console.log(newArr)
                    this.qudaoList = newArr
                }
            });
        },
        getTableData(params = {}) {
            const defaultParams = {
                page: this.currentPage,
                ...params
            };
            this.$message.info({
                message: '正在加载数据...',
                duration: 0,
                showClose: true,
                iconClass: 'el-icon-loading'
            });
            this.$http.get('/admin/UserWeightDiv/lists',{params: defaultParams}).then(result => {
                if (result.code === 200) {
                    this.tableData = result.data.data;
                    this.total = result.data.total || this.tableData.length;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取数据失败，请重试');
            }).finally(() => {
                this.$message.closeAll();
            });
        },
        toggleStatus(row) {
            row.status = row.status ? 0 : 1
        },
        handleSearch() {
            // 过滤空字符串参数
            this.searchParams = this.filterEmptyParams(this.searchForm);
            this.currentPage = 1;
            this.getTableData(this.searchParams);
        },
        handleReset() {
            this.searchForm = {
                date: '',
                is_up: '',
                search: '',
                state: '',
                channel_id:""
            }
            this.getTableData()
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.getTableData()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getTableData(this.searchParams)
        },
        // 点击金额处理
        handleAmountClick(row) {
            this.editForm = {
                userId: row.userId,
                username: row.username || '未知用户',
                originalAmount: row.amount.toFixed(2),
                newAmount: row.amount.toFixed(2),
                rowIndex: this.tableData.indexOf(row)
            }
            this.amountDialogVisible = true
        },
        // 确认修改处理
        handleConfirmEdit() {
            if (!this.editForm.newAmount) {
                this.$message.error('请输入新金额')
                return
            }
            this.confirmDialogVisible = true
        },
        // 处理对话框关闭
        handleDialogClose() {
            this.amountDialogVisible = false
        },
        // 提交金额修改
        submitAmountChange() {
            const index = this.editForm.rowIndex
            if (index > -1 && index < this.tableData.length) {
                this.tableData[index].amount = parseFloat(this.editForm.newAmount)
                this.$message.success('金额修改成功')
            } else {
                this.$message.error('修改失败，找不到对应记录')
            }
            this.confirmDialogVisible = false
            this.amountDialogVisible = false
        },
        // 分红凭证上传成功回调
        handleDivCertSuccess(res) {
            console.log(res)
            if (res.code === 200) {
                this.div_cert = res.data[0];
                this.$message.success('上传成功');
            } else {
                this.$message.error(res.msg || '上传失败');
            }
        },
        beforeDivCertUpload(file) {
            const isImage = file.type.startsWith('image/');
            if (!isImage) {
                this.$message.error('只能上传图片文件!');
            }
            return isImage;
        },
    }
}
</script>

<style scoped lang="less">
.admin-page {
    padding: 20px;

    .search-label {
        margin-right: 10px;
        color: #606266;
    }

    .el-table {
        margin-top: 20px;
    }

    .el-pagination {
        margin-top: 20px;
        text-align: right;
    }

    .clickable-amount {
        color: #409EFF;
        cursor: pointer;
        font-weight: bold;

        &:hover {
            text-decoration: underline;
        }
    }
}

.amount-edit-dialog {
    border-radius: 8px;
    overflow: hidden;

    /deep/ .el-dialog__header {
        background-color: #f5f7fa;
        padding: 15px 20px;

        .el-dialog__title {
            font-weight: bold;
            color: #303133;
        }
    }

    /deep/ .el-dialog__body {
        padding: 25px 20px 10px;
    }

    .edit-form {
        margin-top: 10px;

        /deep/ .el-form-item__label {
            font-weight: 500;
            color: #606266;
        }

        .info-item {
            /deep/ .el-input__inner {
                background-color: #f5f7fa;
                color: #606266;
            }
        }
    }

    /deep/ .el-dialog__footer {
        border-top: 1px solid #ebeef5;
        padding: 15px 20px;
    }

    .dialog-footer {
        text-align: right;
    }
}

.confirm-dialog {
    border-radius: 8px;

    /deep/ .el-dialog__header {
        padding: 15px 20px;
    }

    /deep/ .el-dialog__body {
        padding: 10px 40px;
    }

    .confirm-content {
        //display: flex;
        //align-items: flex-start;
        margin-bottom: 15px;

        .warning-icon {
            font-size: 24px;
            color: #E6A23C;
            margin-right: 15px;
            margin-top: 3px;
        }

        .confirm-text {
            flex: 1;

            .confirm-title {
                font-size: 16px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 5px;
            }

            .confirm-desc {
                color: #606266;
                line-height: 1.5;
            }
        }
    }

    .confirm-details {
        background-color: #f8f8f8;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 10px;

        .detail-item {
            display: flex;
            margin-bottom: 8px;

            &:last-child {
                margin-bottom: 0;
            }

            .detail-label {
                width: 70px;
                color: #909399;
            }

            .detail-value {
                flex: 1;
                color: #303133;
                font-weight: 500;
            }
        }
    }
}

/deep/ .el-dialog__header{
    padding: 10px !important;
}

.confirm-dialog {
    .el-dialog__header {
        background-color: #f5f7fa;
        border-bottom: 1px solid #ebeef5;
    }

    .el-dialog__title {
        font-weight: bold;
        color: #303133;
    }

    .el-dialog__content {
        padding: 30px 20px;
    }
}

.confirm-content {
    padding: 10px 0;

    .confirm-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        font-size: 14px;

        .value {
            margin-left: 10px;
            font-weight: bold;
            color: #303133;
        }
    }
}

.danger {
    .el-dialog__header {
        background-color: #fef0f0;
        border-color: #fde2e2;
    }

    .el-dialog__title {
        color: #f56c6c;
    }

    .confirm-content {
        .warning-text {
            color: #f56c6c;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .confirm-item {
            .value {
                color: #f56c6c;
            }
        }
    }
}
/deep/ .el-dialog__header{
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
